package com.blacktea.structuralpatterns.compositepattern.component;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;

/**
 * @description: 组合组件类
 * @author: black tea
 * @date: 2023/3/22 17:53
 */
@Slf4j
public class Composite<T> extends Component<T> {

    private List<Component<T>> children = new ArrayList<>();

    public Composite(String name, Consumer<T> consumer) {
        super(name, consumer);
    }

    @Override
    public void operation(T data){
        Optional.ofNullable(consumer)
                .ifPresent(c -> c.accept(data));
        startForEachComponent(data);
    }

    public void add(Component<T> component) {
        children.add(component);
    }

    public void remove(Component<T> component) {
        children.remove(component);
    }

    public void addAll(Collection<Component<T>> components){
        children.addAll(components);
    }

    private void startForEachComponent(T data){
        log.info("【{}】，开始执行所有组件。", this.name);
        children.forEach(component -> {
            log.info("执行【{}】组件", component.name);
            component.operation(data);
        });
        log.info("【{}】,结束执行所有组件。", this.name);
    }
}
